package utils;


import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import javax.xml.xpath.XPathExpressionException;


import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import org.w3c.dom.Text;
import org.xml.sax.SAXException;

import client.Client;

import file.File;

public class SavedData{

	static private String pathToSavedFile = "resources/saved.xml";

	public static void newPath(String path) throws ParserConfigurationException, TransformerException, IOException{
		pathToSavedFile = path;
		clear();
	}

	public static void save(File f) throws XPathExpressionException, ParserConfigurationException, SAXException, IOException, TransformerException{
		DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
		domFactory.setNamespaceAware(true); 
		DocumentBuilder builder;

		builder = domFactory.newDocumentBuilder();
		Document doc;
		//	Recuperation du XML existant ou création du XML
		try{
			doc = builder.parse(pathToSavedFile);
		}
		catch(FileNotFoundException e){
			clear();
			doc = builder.parse(pathToSavedFile);
		}
		Element leeches =(Element) doc.getElementsByTagName("leeches").item(0);
		Element seeds = (Element) doc.getElementsByTagName("seeds").item(0);

		//Creation du nouveau noeud
		Element file = doc.createElement("file");  
		file.setAttribute("id",f.getIdFile());	


		Element name = doc.createElement("name");
		file.appendChild(name);
		Text sName = doc.createTextNode(f.getName());
		name.appendChild(sName);

		Element path = doc.createElement("path");
		file.appendChild(path);
		Text sPath = doc.createTextNode(f.getPath());
		
		path.appendChild(sPath);
		
		Element size = doc.createElement("size");
		file.appendChild(size);
		Text sSize = doc.createTextNode(String.valueOf(f.getSize()));
		size.appendChild(sSize);

		Element pieceSize = doc.createElement("pieceSize");
		file.appendChild(pieceSize);
		Text sPieceSize = doc.createTextNode(String.valueOf(f.getPieceSize()));
		pieceSize.appendChild(sPieceSize);

		//On regarde où mettre le nouveau noeud et s'il existe déjà on le remplace
		if(f.getBufferMap().getLength() == f.getBufferMap().getBufferMap().cardinality()){

			NodeList seedFiles = doc.getElementsByTagName("file");
			int i = 0;
			while(i<seedFiles.getLength()){

				if(seedFiles.item(i).getAttributes().getNamedItem("id").getTextContent().equals(f.getIdFile()))
					seeds.replaceChild(file,seedFiles.item(i));
				i++;
			}
			if(i == seedFiles.getLength())
				seeds.appendChild(file);
		}
		else{
			NodeList leechFiles = doc.getElementsByTagName("file");
			int i = 0;
			while(i<leechFiles.getLength()){

				if(leechFiles.item(i).getAttributes().getNamedItem("id").getTextContent().equals(f.getIdFile()))
					leeches.replaceChild(file,leechFiles.item(i));
				i++;
			}
			if(i == leechFiles.getLength())
				leeches.appendChild(file);
		}
		/////////////////
		//Output the XML

		//set up a transformer
		TransformerFactory transfac = TransformerFactory.newInstance();
		Transformer trans = transfac.newTransformer();
		trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
		trans.setOutputProperty(OutputKeys.INDENT, "yes");

		StringWriter sw = new StringWriter();
		StreamResult result = new StreamResult(sw);
		DOMSource source = new DOMSource(doc);
		trans.transform(source, result);
		String xmlString = sw.toString();

		BufferedWriter out = new BufferedWriter(new FileWriter(pathToSavedFile));
		out.write(xmlString);
		out.close();
	}

public static void loadIn(Client c) throws ParserConfigurationException, SAXException, IOException, TransformerException{
		DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
		domFactory.setNamespaceAware(true); 
		DocumentBuilder builder;

		builder = domFactory.newDocumentBuilder();
		Document doc;
		//	Recuperation du XML existant ou création du XML
		try{
			doc = builder.parse(pathToSavedFile);
		}
		catch(FileNotFoundException e){
			clear();
			doc = builder.parse(pathToSavedFile);
		}
		Element leeches =(Element) doc.getElementsByTagName("leeches").item(0);
		Element seeds = (Element) doc.getElementsByTagName("seeds").item(0);

		NodeList myLeeches = leeches.getElementsByTagName("file");
		NodeList mySeeds= seeds.getElementsByTagName("file");
		
		ArrayList<File> myLeech = new ArrayList<File>();
		
		for(int i = 0; i< myLeeches.getLength();i++){
			String id = myLeeches.item(i).getAttributes().item(0).getNodeValue();
			String pieceSize = myLeeches.item(i).getChildNodes().item(0).getTextContent();
			String name = myLeeches.item(i).getChildNodes().item(1).getTextContent();
			String size = myLeeches.item(i).getChildNodes().item(2).getTextContent();
			String path = myLeeches.item(i).getChildNodes().item(3).getTextContent();
			
			File f = new File();
			f.setIdFile(id);
			f.setName(name);
			f.setPath(path);	
			try{
				f.setSize(Integer.parseInt(size));
				}catch(NumberFormatException e){
					f.setSize(-1);
				}
				try{
					f.setPieceSize(Integer.parseInt(pieceSize));
					}catch(NumberFormatException e){
						f.setPieceSize(-1);
					}
			
			myLeech.add(f);
		}
		c.setMyLeech(myLeech);
		
ArrayList<File> mySeed = new ArrayList<File>();
		
		for(int i = 0; i< mySeeds.getLength();i++){
			String id = mySeeds.item(i).getAttributes().item(0).getNodeValue();
			String pieceSize = mySeeds.item(i).getChildNodes().item(0).getTextContent();
			String name = mySeeds.item(i).getChildNodes().item(1).getTextContent();
			String size = mySeeds.item(i).getChildNodes().item(2).getTextContent();
			String path = mySeeds.item(i).getChildNodes().item(3).getTextContent();
			
			File f = new File();
			f.setIdFile(id);
			f.setName(name);
			f.setPath(path);	
			try{
			f.setSize(Integer.parseInt(size));
			}catch(NumberFormatException e){
				f.setSize(-1);
			}
			try{
				f.setPieceSize(Integer.parseInt(pieceSize));
				}catch(NumberFormatException e){
					f.setPieceSize(-1);
				}
			mySeed.add(f);
		}
		c.setMySeed(mySeed);
	}
	
public static void clear() throws ParserConfigurationException, TransformerException, IOException{
		DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
		domFactory.setNamespaceAware(true); 
		DocumentBuilder builder;

		builder = domFactory.newDocumentBuilder();
		//	Creation du XML
		Document doc = builder.newDocument();
		Element root = doc.createElement("saved-pony2pony");
		Element leeches = doc.createElement("leeches");
		Element seeds = doc.createElement("seeds");
		doc.appendChild(root);
		root.appendChild(leeches);
		root.appendChild(seeds);

		/////////////////
		//Output the XML

		//set up a transformer
		TransformerFactory transfac = TransformerFactory.newInstance();
		Transformer trans = transfac.newTransformer();
		trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
		trans.setOutputProperty(OutputKeys.INDENT, "yes");

		StringWriter sw = new StringWriter();
		StreamResult result = new StreamResult(sw);
		DOMSource source = new DOMSource(doc);
		trans.transform(source, result);
		String xmlString = sw.toString();

		BufferedWriter out = new BufferedWriter(new FileWriter(pathToSavedFile) );
		out.write(xmlString);
		out.close();
	}

public static void removeFile(){
	java.io.File savedFile = new java.io.File(pathToSavedFile); 
	savedFile.delete(); 
}


}




